package com.zhixue.base.exception;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Dragon
 * @description 全局异常处理器
 * @date 2023/9/20 20:13
 */
@Slf4j
@RestControllerAdvice  //@ControllerAdvice + @ResponseBody
public class GlobalExceptionHandler {


    /**
     * 自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(ZhiXueException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)   // 该异常枚举错误码为500
    public RestErrorResponse customException(ZhiXueException e) {
        log.error("【系统异常】{}",e.getErrMessage(),e);
        e.printStackTrace();
        return new RestErrorResponse(e.getErrMessage());

    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse exception(Exception e) {
        log.error("【系统异常】{}",e.getMessage(),e);
        e.printStackTrace();
        //不选择将该异常捕获来处理，是因为处理org。springframework.security.AccessDeniedException 得先引入spring security的依赖包，就会导致概模块被管控
        if ("不允许访问".equals(e.getMessage()))
            return new RestErrorResponse("您没有权限操作此功能");
        return new RestErrorResponse(CommonError.UNKOWN_ERROR.getErrMessage());

    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse doMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
        BindingResult bindingResult = exception.getBindingResult();
//        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
//        StringBuffer stringBuffer = new StringBuffer();
//        fieldErrors.forEach(fieldError -> stringBuffer.append(fieldError.getDefaultMessage()).append(","));
//        log.error("【系统异常】{}",stringBuffer.toString());
//        return new RestErrorResponse(stringBuffer.toString());
        List<String> errors = new ArrayList<>();
        //将错误信息放在msgList
        bindingResult.getFieldErrors().stream().forEach(item->errors.add(item.getDefaultMessage()));
        //拼接错误信息
        String msg = StringUtils.join(errors, ",");
        log.error("【系统异常】{}",msg);
        return new RestErrorResponse(msg);


    }
}
